package com.tihi.uiautomator;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PathEffect;
import android.graphics.RectF;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;

import com.tihi.util.AppUtils;

/**
 * 截屏上的标记 view
 * @author duantihi
 *
 * @date 2016-2-1 上午11:05:34
 */
public class UIMarkView extends View{
	private RectF drawRectF;
	private Paint boundsPaint;
	private TextPaint textPaint;
	private Paint textBgPaint;
	private String boundsText;
	
    public UIMarkView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

	public UIMarkView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init();
	}
	
	private void init() {
		//边框画笔
		boundsPaint = new Paint();
		boundsPaint.setAntiAlias(true);
		boundsPaint.setStrokeWidth(3);
		PathEffect effects = new DashPathEffect(new float[] {5,5,5,5}, 1);
		boundsPaint.setPathEffect(effects);
		boundsPaint.setStyle(Style.STROKE);
		boundsPaint.setColor(Color.RED);
		
		//bounds文字画笔
		textPaint = new TextPaint();
		textPaint.setAntiAlias(true);
		textPaint.setTextSize(24);
		textPaint.setColor(Color.WHITE);
		
		//bounds文字背景画笔
		textBgPaint = new Paint();
		textBgPaint.setAntiAlias(true);
		textBgPaint.setColor(Color.parseColor("#880000FF"));
		textBgPaint.setStyle(Style.FILL);
		
		drawRectF = new RectF();
	}
	
	public void setDrawArea(float left, float top, float right, float bottom) {
		drawRectF = new RectF(left, top, right, bottom);
		invalidate();
	}
	
	public void setDrawArea(RectF rectF) {
		this.drawRectF = rectF;
		invalidate();
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		//清除画布后再画
		super.onDraw(canvas);
		if(!drawRectF.isEmpty()) {
			//画bounds矩形
			canvas.drawRect(drawRectF, boundsPaint);
			
			boundsText = "[" + AppUtils.formatFloat(drawRectF.left) + ", " + AppUtils.formatFloat(drawRectF.top) + "]" +
						"[" + AppUtils.formatFloat(drawRectF.right) + ", " + AppUtils.formatFloat(drawRectF.bottom ) + "]";
			
			//画bounds文字背景
			canvas.drawRect(getTextBounds(boundsText), textBgPaint);
			
			//画bounds文字
			canvas.drawText(boundsText, drawRectF.left + 5, drawRectF.top + 36, textPaint);
		}
	}
	
	private RectF getTextBounds(String text) {
		RectF rectF = new RectF();
		rectF.left = drawRectF.left + 5;
		rectF.top = drawRectF.top + 10;
		rectF.right = rectF.left + textPaint.measureText(text) + 5;
		rectF.bottom = rectF.top + 38;
		
		return rectF;
	}
	
}
